package com.j2eefast.flowable.bpm.service;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.j2eefast.common.core.utils.ResponseData;
import com.j2eefast.flowable.bpm.entity.BpmBidLaborSettlementEntity;
import com.j2eefast.flowable.bpm.entity.BpmFormDraftEntity;
import com.j2eefast.flowable.bpm.entity.StartProcessInstanceEntity;
import com.j2eefast.flowable.bpm.mapper.BpmBidLaborSettlementeMapper;
import com.j2eefast.framework.utils.UserUtils;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * 项目验收资料盖章申请表Service接口
 * @author: SUMMER
 * @date 2021-06-4 22:19
 */
@Service
public class BpmBidLaborSettlementService extends ServiceImpl<BpmBidLaborSettlementeMapper, BpmBidLaborSettlementEntity> {

	@Resource
	@Lazy
	private BpmBidLaborSettlementService bpmBidLaborSettlementService;

	@Autowired
	private FlowableProcessInstanceService flowableProcessInstanceService;
	@Autowired
	private BpmFormDraftService bpmFormDraftService;

	/**
	 * 保存表单并发起审批
	 */
	@Transactional(rollbackFor = Exception.class)
	public ResponseData addForm(BpmBidLaborSettlementEntity bpmBidLaborSettlementEntity){
		//请填写 这三个字段 ProcessDefinitionKey,BusinessKey,SystemSn
		bpmBidLaborSettlementEntity.setId(IdUtil.fastSimpleUUID());
		bpmBidLaborSettlementEntity.setUserId(String.valueOf(UserUtils.getUserId()));
		bpmBidLaborSettlementEntity.setTitle(this.formatTitle(bpmBidLaborSettlementEntity.getTitle(), bpmBidLaborSettlementEntity));
		ResponseData returnStart = this.startProcess(bpmBidLaborSettlementEntity);
		if(!returnStart.get("code").equals("00000")) {
			return returnStart;
		}
		String processInstanceId = ((ProcessInstance)returnStart.get("data")).getProcessInstanceId();

		bpmBidLaborSettlementEntity.setProcessInstanceId(processInstanceId);
		BpmFormDraftEntity bpmFormDraftEntity = this.prepareFormDraft(bpmBidLaborSettlementEntity,false);
		bpmFormDraftService.save(bpmFormDraftEntity);
		return bpmBidLaborSettlementService.save(bpmBidLaborSettlementEntity)? ResponseData.success(): ResponseData.error("数据插入失败!");
	}

	/**
	 * 根居ID获取对象
	 */
	public BpmBidLaborSettlementEntity getFormById(String id){
		return this.getById(id);
	}


	protected String formatTitle(String title, BpmBidLaborSettlementEntity bpmBidLaborSettlementEntity){
		//项目报备申请-{创建人}（{创建时间}）
		title = title.replace("{年月}", bpmBidLaborSettlementEntity.getMonth());
		title = title.replace("{项目经理}", bpmBidLaborSettlementEntity.getProjectAdmin());
		title = title.replace("{创建人}", bpmBidLaborSettlementEntity.getLaunchName());
		title = title.replace("{应交款合计}", bpmBidLaborSettlementEntity.getAmount());
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String dateString = formatter.format(bpmBidLaborSettlementEntity.getCreateTime());
		return title.replace("{创建时间}", dateString);
	}



	/**
	 * 启动流程实例
	 * @param bpmBidLaborSettlementEntity
	 * @return
	 */
	private ResponseData startProcess(BpmBidLaborSettlementEntity bpmBidLaborSettlementEntity){
		//请填写 这三个字段 ProcessDefinitionKey,BusinessKey,SystemSn
		StartProcessInstanceEntity startProcessInstanceVo = new StartProcessInstanceEntity();
		startProcessInstanceVo.setBusinessKey(bpmBidLaborSettlementEntity.getId());
		startProcessInstanceVo.setCreator(String.valueOf(UserUtils.getUserId()));
		startProcessInstanceVo.setCurrentUserCode(String.valueOf(UserUtils.getUserId()));
		startProcessInstanceVo.setFormName(bpmBidLaborSettlementEntity.getTitle());
		startProcessInstanceVo.setSystemSn("system");
		//startProcessInstanceVo.setProcessDefinitionKey(bpmBidOpeningEntity.getModelKey());
		startProcessInstanceVo.setProcessDefinitionKey(bpmBidLaborSettlementEntity.getModelKey());
		Map<String, Object> variables = new HashMap<>();
		variables.put("priority", bpmBidLaborSettlementEntity.getPriority());
		startProcessInstanceVo.setVariables(variables);
		return flowableProcessInstanceService.startProcessInstanceByKey(startProcessInstanceVo);
	}


	public BpmFormDraftEntity prepareFormDraft(BpmBidLaborSettlementEntity bpmBidLaborSettlementEntity, boolean active){
		//写入草稿
		BpmFormDraftEntity bpmFormDraftEntity = new BpmFormDraftEntity();
		bpmFormDraftEntity.setTitle(bpmBidLaborSettlementEntity.getTitle());
		bpmFormDraftEntity.setUserId(String.valueOf(UserUtils.getUserId()));
		//这是一个固定的数据，每个表单表有一个url prefix
		bpmFormDraftEntity.setUrl("bpm/bidlaborsettlement");
		bpmFormDraftEntity.setStatus("1");
		bpmFormDraftEntity.setPriority(bpmBidLaborSettlementEntity.getPriority());
		bpmFormDraftEntity.setFormDataId(bpmBidLaborSettlementEntity.getId());
		bpmFormDraftEntity.setCreateTime(new Date());
		if(bpmBidLaborSettlementEntity.getProcessInstanceId()!=null){
			bpmFormDraftEntity.setProcessInstanceId(bpmBidLaborSettlementEntity.getProcessInstanceId());
		}
		String activeFlag = active?"1":"0";
		bpmFormDraftEntity.setActive(activeFlag);
		return bpmFormDraftEntity;
	}


	/**
	 * 将表单进行保存，不发起流程
	 * @param bpmBidLaborSettlementEntity
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public ResponseData saveAsDraft(BpmBidLaborSettlementEntity bpmBidLaborSettlementEntity){
		//请填写 这三个字段 ProcessDefinitionKey,BusinessKey,SystemSn
		bpmBidLaborSettlementEntity.setId(IdUtil.fastSimpleUUID());
		bpmBidLaborSettlementEntity.setUserId(String.valueOf(UserUtils.getUserId()));
		bpmBidLaborSettlementEntity.setTitle(this.formatTitle(bpmBidLaborSettlementEntity.getTitle(), bpmBidLaborSettlementEntity));
		bpmBidLaborSettlementEntity.setStatus("0");
		//写入草稿数据
		BpmFormDraftEntity bpmFormDraftEntity = this.prepareFormDraft(bpmBidLaborSettlementEntity,true);
		bpmFormDraftService.save(bpmFormDraftEntity);
		return bpmBidLaborSettlementService.save(bpmBidLaborSettlementEntity)? ResponseData.success(): ResponseData.error("数据插入失败!");
	}

	/**
	 * 将待发表单重新发起流程
	 * @param formDraftId
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public ResponseData sendForm(String formDraftId){
		//更新FormDraft的状态
		BpmFormDraftEntity bpmFormDraftEntity = bpmFormDraftService.getById(formDraftId);
		BpmFormDraftEntity toUpdateDraft = new BpmFormDraftEntity();
		toUpdateDraft.setStatus("2");
		toUpdateDraft.setId(bpmFormDraftEntity.getId());
		bpmFormDraftService.updateDataById(toUpdateDraft);
		BpmBidLaborSettlementEntity bpmBidLabourEntity = bpmBidLaborSettlementService.getFormById(bpmFormDraftEntity.getFormDataId());
		//请填写 这三个字段 ProcessDefinitionKey,BusinessKey,SystemSn
		ResponseData returnStart = this.startProcess(bpmBidLabourEntity);
		if(!returnStart.get("code").equals("00000")){
			return returnStart;
		}
		BpmBidLaborSettlementEntity toUpdate = new BpmBidLaborSettlementEntity();
		toUpdate.setId(bpmBidLabourEntity.getId());
		toUpdate.setProcessInstanceId(((ProcessInstance)returnStart.get("data")).getProcessInstanceId());
		return bpmBidLaborSettlementService.updateById(toUpdate)? ResponseData.success(): ResponseData.error("发起流程失败!");
	}


	/**
	 * 修改未发起审批的表单
	 * @param
	 * @return
	 */
	public boolean editForm(BpmBidLaborSettlementEntity bpmBidLaborSettlementEntity){
		BpmFormDraftEntity bpmFormDraftEntity = bpmBidLaborSettlementService.prepareFormDraft(bpmBidLaborSettlementEntity, true);
		bpmFormDraftService.updateByFormDataId(bpmFormDraftEntity);
		return this.updateById(bpmBidLaborSettlementEntity);
	}





	}